package org.openanypcao.cs.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.openanypcao.cs.core.GeneralConstant;
import org.openanypcao.cs.core.HttpConnection;
import org.openanypcao.cs.core.LogManager;
import org.openanypcao.cs.service.IExpManager;
import org.openanypcao.cs.util.StringUtil;


/**
 * 
 *作者：曹正标</p>
 *日期：2011-12-29</p>
 *功能：通用实验管理器</p>
 */
public class GenericExpManagerImpl implements IExpManager {

	//日志管理器
	protected static Logger logger = LogManager.getLogger(GenericExpManagerImpl.class);
	
	/**
	 * 
	 * 作  者：曹正标</p>
	 * 功  能：函数断言</p>
	 * 参  数：</p>
	 * 返回值：</p>
	 * @return void
	 * 修改记录： </p>
	 * 修改日期：</p>
	 * 修改人：</p>
	 * 修改概述：</p>
	 */
	protected void assertMethod(){
		assert !StringUtil.isBlank(GeneralConstant.HOST_URL) : "Please login!";
		assert !StringUtil.isBlank(GeneralConstant.ACCOUNT) : "Please login!";
		assert !StringUtil.isBlank(GeneralConstant.PASSWORD) : "Please login!";
	}
	
	@Override
	public String login(String account, String password) {
		try {
			GeneralConstant.ACCOUNT = account;
			GeneralConstant.PASSWORD = password;
			
			String requestPath = GeneralConstant.HOST_URL+"/lab/client/!login";
			Map<String, String[]> params = new HashMap<String, String[]>();
			params.put("account", new String[]{account});
			params.put("password", new String[]{password});
			
			HttpURLConnection connection = HttpConnection.doPost(requestPath, params);
					
			//接收服务器返回信息
			return getStringInStream(connection);
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}
		return null;
	}
	
	@Override
	public String getExps(String studentId) {
		try {
			String requestPath = GeneralConstant.HOST_URL+"/lab/client/!studentExps";
			Map<String, String[]> params = new HashMap<String, String[]>();
			params.put("userId", new String[]{studentId});
			HttpURLConnection connection = HttpConnection.doGet(requestPath, params);
			//接收服务器返回信息
			return getStringInStream(connection);
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}
		return null;
	}
	
	@Override
	public String teacherGrades(String teacherId) {
		try {
			String requestPath = GeneralConstant.HOST_URL+"/lab/client/!teacherGrades";
			Map<String, String[]> params = new HashMap<String, String[]>();
			params.put("userId", new String[]{teacherId});
			HttpURLConnection connection = HttpConnection.doGet(requestPath, params);
			//接收服务器返回信息
			return getStringInStream(connection);
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}
		return null;
	}
	
	@Override
	public String teacherExps(String teacherId, String grade, String term) {
		try {
			String requestPath = GeneralConstant.HOST_URL+"/lab/client/!teacherExps";
			Map<String, String[]> params = new HashMap<String, String[]>();
			params.put("userId", new String[]{teacherId});
			params.put("grade", new String[]{grade});
			params.put("term", new String[]{term});
			HttpURLConnection connection = HttpConnection.doGet(requestPath, params);
			//接收服务器返回信息
			return getStringInStream(connection);
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}
		return null;
	}
	
	@Override
	public String expStudents(String classId) {
		try {
			String requestPath = GeneralConstant.HOST_URL+"/lab/client/!expStudents";
			Map<String, String[]> params = new HashMap<String, String[]>();
			params.put("classId", new String[]{classId});
			HttpURLConnection connection = HttpConnection.doGet(requestPath, params);
			//接收服务器返回信息
			return getStringInStream(connection);
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}
		return null;
	}
	
	@Override
	public String commitOutcome(String expId, String studentId, String outcome) {
		try {
			String requestPath = GeneralConstant.HOST_URL+"/lab/client/!commitOutcome";
			Map<String, String[]> params = new HashMap<String, String[]>();
			params.put("expId", new String[]{expId});
			params.put("userId", new String[]{studentId});
			params.put("outcome", new String[]{outcome});
			HttpURLConnection connection = HttpConnection.doPost(requestPath, params);
			//接收服务器返回信息
			return getStringInStream(connection);
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}
		return null;
	}
	
	@Override
	public String commitCorrect(String expId, String studentId, double score,
			String remark) {
		try {
			String requestPath = GeneralConstant.HOST_URL+"/lab/client/!commitCorrect";
			Map<String, String[]> params = new HashMap<String, String[]>();
			params.put("expId", new String[]{expId});
			params.put("userId", new String[]{studentId});
			params.put("score", new String[]{""+score});
			params.put("remark", new String[]{remark});
			HttpURLConnection connection = HttpConnection.doPost(requestPath, params);
			//接收服务器返回信息
			return getStringInStream(connection);
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}
		return null;
	}
	
	@Override
	public String studentOutcome(String expId, String studentId) {
		try {
			String requestPath = GeneralConstant.HOST_URL+"/lab/client/!studentOutcome";
			Map<String, String[]> params = new HashMap<String, String[]>();
			params.put("expId", new String[]{expId});
			params.put("userId", new String[]{studentId});
			HttpURLConnection connection = HttpConnection.doGet(requestPath, params);
			//接收服务器返回信息
			return getStringInStream(connection);
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}
		return null;
	}

	
	
	@Override
	public void downloadExpFile(String srcPath, String destPath) {
		assertMethod();
		
		String requestPath = GeneralConstant.HOST_URL+srcPath;
		HttpURLConnection connection = null;
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			connection = HttpConnection.doGet(requestPath, null);
			String contentDisposition = connection.getHeaderField("Content-Disposition");
			String[] s = contentDisposition.split("\"");
			String fileName = URLDecoder.decode(s[1],GeneralConstant.DEFAULT_ENCODE);
			in = new BufferedInputStream(connection.getInputStream());
			out = new BufferedOutputStream(new FileOutputStream(new File(destPath+fileName)));
			byte[] data = new byte[8192];
			int len = 0;
			while((len = in.read(data)) != -1){
				out.write(data, 0, len);
			}
			
		} catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
				}
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
				}
			}
			if(connection != null){
				connection.disconnect();
			}
		}
	}
	
	/**
	 * 从connection中获得返回的信息并转化为String格式
	 * @param connection
	 * @return
	 */
	public static String getStringInStream(HttpURLConnection connection){
		String sso_user_info = "";
		BufferedInputStream in = null;
		ByteArrayOutputStream out = null;
		try{
		in = new BufferedInputStream(connection.getInputStream());
		out = new ByteArrayOutputStream();
		byte[] buffer = new byte[8192];
		int length = 0;
		do {
			length = in.read(buffer);
			if (length == -1) {
				break;
			}
			out.write(buffer, 0, length);
		} while (true);
		sso_user_info = out.toString(GeneralConstant.DEFAULT_ENCODE);
		}catch (IOException e) {
			logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
		}finally{
			try {
				if(in != null){
					in.close();
				}
			} catch (IOException e) {
				logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
			}
			try {
				if(out != null){
					out.close();
				}
			} catch (IOException e) {
				logger.log(Level.SEVERE, StringUtil.getTraceOfException(e));
			}
			if(connection != null){
				connection.disconnect();
			}
		}
		return sso_user_info;
	}

}
